package com.zs.hydrant.controller;


import com.zs.hydrant.entity.User;
import com.zs.hydrant.md5Util;
import com.zs.hydrant.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    // 登录接口
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, Object> param) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 从请求参数中获取手机号、密码和角色
            String phone = (String) param.get("phone");
            String password = (String) param.get("password");
            Integer role = (Integer) param.get("role");
            password = md5Util.md5Encode(password.toString());
            // 调用Service层进行登录验证
            User user = userService.login(phone, password, role);

            if (user != null) {
                result.put("success", true);
                result.put("msg", "登录成功");
                // 构建用户信息，不返回密码
                Map<String, Object> userInfo = new HashMap<>();
                userInfo.put("id", user.getId());
                userInfo.put("username", user.getUsername());
                userInfo.put("phone", user.getPhone());
                userInfo.put("role", user.getRole());
                result.put("data", userInfo);
                result.put("code", 200);
            } else {
                result.put("success", false);
                result.put("msg", "手机号或密码错误");
                result.put("code", 400);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("msg", "登录失败：" + e.getMessage());
            result.put("code", 500);
        }
        return result;
    }

    // 获取角色列表
    @GetMapping("/roleList")
    public Map<String, Object> roleList() {
        Map<String, Object> result = new HashMap<>();
        try {
            // 构建角色列表
            List<Map<String, Object>> roleList = new ArrayList<>();
            Map<String, Object> role1 = new HashMap<>();
            role1.put("id", 1);
            role1.put("name", "消防员");
            roleList.add(role1);

            Map<String, Object> role2 = new HashMap<>();
            role2.put("id", 2);
            role2.put("name", "采集人员");
            roleList.add(role2);

            Map<String, Object> role3 = new HashMap<>();
            role3.put("id", 3);
            role3.put("name", "管理员");
            roleList.add(role3);

            Map<String, Object> role4 = new HashMap<>();
            role4.put("id", 4);
            role4.put("name", "高级管理员");
            roleList.add(role4);

            result.put("success", true);
            result.put("msg", "获取成功");
            result.put("data", roleList);
            result.put("total", roleList.size());
            result.put("code", 200);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("msg", "获取失败：" + e.getMessage());
            result.put("code", 500);
        }
        return result;
    }

    // 分配角色接口
    @PostMapping("/assignRole")
    public Map<String, Object> assignRole(@RequestBody Map<String, Object> param) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取参数
            String name = (String) param.get("name");
            String phone = (String) param.get("phone");
            Integer role = (Integer) param.get("role");

            // 参数校验
            if (name == null || name.isEmpty()) {
                result.put("success", false);
                result.put("msg", "姓名不能为空");
                result.put("code", 400);
                return result;
            }
            if (phone == null || phone.isEmpty()) {
                result.put("success", false);
                result.put("msg", "手机号不能为空");
                result.put("code", 400);
                return result;
            }
            if (role == null) {
                result.put("success", false);
                result.put("msg", "角色不能为空");
                result.put("code", 400);
                return result;
            }

            // 调用Service层更新角色
            boolean updateResult = userService.updateRoleByPhone(phone, role);

            if (updateResult) {
                result.put("success", true);
                result.put("msg", "角色分配成功");
                result.put("code", 200);
            } else {
                result.put("success", false);
                result.put("msg", "角色分配失败，用户不存在");
                result.put("code", 400);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("msg", "角色分配失败：" + e.getMessage());
            result.put("code", 500);
        }
        return result;
    }

    // 1. 获取所有用户列表
    @GetMapping("/list")
    public Map<String, Object> getAllUsers() {
        Map<String, Object> result = new HashMap<>();

        // 查询所有用户（排除密码字段，避免泄露）
        List<User> userList = userService.list();
        // 遍历列表，清空密码（前端无需展示密码）
        userList.forEach(user -> user.setPassword(null));

        result.put("code", 200);
        result.put("msg", "获取成功");
        result.put("data", userList);
        return result;
    }

    // 2. 删除用户
    @PostMapping("/delete")
    public Map<String, Object> deleteUser(@RequestBody Map<String, Integer> params) {
        Map<String, Object> result = new HashMap<>();
        Integer userId = params.get("id");

        // 执行删除
        boolean success = userService.removeById(userId);
        if (success) {
            result.put("code", 200);
            result.put("msg", "删除成功");
        } else {
            result.put("code", 500);
            result.put("msg", "删除失败（用户不存在）");
        }
        return result;
    }

    // 3. 修改用户状态（0正常 ↔ 1禁用）
    @PostMapping("/updateStatus")
    public Map<String, Object> updateStatus(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        Integer userId = (Integer) params.get("id");
        Integer newStatus = (Integer) params.get("status");

        // 执行状态更新
        User user = new User();
        user.setId(userId);
        user.setStatus(newStatus);
        boolean success = userService.updateStatusById(user);

        if (success) {
            result.put("code", 200);
            result.put("msg", newStatus == 0 ? "启用成功" : "禁用成功");
        } else {
            result.put("code", 500);
            result.put("msg", "状态更新失败");
        }
        return result;
    }


}